<template>
	<view class="uploader-wrapper">
		<van-grid column-num="3" :border="false">
			<van-grid-item use-slot v-for="(item, index) in fileList" :key="index">
				<view class="relative">
					<van-image width="160rpx" height="160rpx" :src="item.url" />
					<view class="close-icon" @click="handleRemoveImage(index)">
						<van-icon
							name="https://ppl.xnue.cn/uploads/20241128/7490f498f01a5b533f7388d2f7aa4ec7.png"></van-icon>
					</view>
				</view>
			</van-grid-item>
		</van-grid>

		<van-uploader v-if="fileList.length < maxCount" :preview-image="false" :file-list="fileList"
			@after-read="handleAfterRead" :deletable="true" accept="image" :multiple="true" :max-count="maxCount">
			<view class="ppl-uploader flex-column-c">
				<view>
					<van-image width="120rpx" height="120rpx" src="../../../static/image/upload.png" />
					<view class="t-12 color2 text-center">
						添加照片
					</view>
				</view>
			</view>
		</van-uploader>
	</view>
</template>

<script setup>
	import {
		ref,
		defineProps,
		defineEmits,
		watch
	} from 'vue';
	import uploadRequest from '@/utils/uploadRequest.js';
	import {
		onHide
	} from '@dcloudio/uni-app';

	const props = defineProps({
		maxCount: {
			type: Number,
			default: 5
		},
		initialFiles: {
			type: Array,
			default: () => []
		}
	});

	const emits = defineEmits(['file-change']);

	// 维护文件列表状态
	const fileList = ref(props.initialFiles.map(file => ({
		url: file.url || file,
		type: 'image'
	})));

	// 添加一个状态变量来跟踪上传中的图片
	const uploading = ref(false);

	// 修改图片上传处理函数
	const handleAfterRead = async (event) => {
		// 获取选择的文件数组
		const files = Array.isArray(event.detail.file) ? event.detail.file : [event.detail.file];

		if (files.length === 0) return;

		// 标记正在上传
		uploading.value = true;

		// 显示上传中提示
		uni.showLoading({
			title: '上传中...',
			mask: true
		});

		try {
			// 用于存储上传成功的图片URL
			const newFileList = [...fileList.value];

			// 逐个上传图片
			for (const item of files) {
				// 添加临时文件用于预览
				const tempFile = {
					url: item.tempFilePath,
					type: 'image',
					temp: true,
					uploading: true
				};

				newFileList.push(tempFile);

				// 更新文件列表以显示临时图片
				fileList.value = newFileList;

				// 上传图片
				const response = await uploadRequest({
					url: "/api/front/hitch/passengerManager/uploadAvatar",
					filePath: item.tempFilePath,
					formData: {
						file: item.tempFilePath
					},
					header: {
						"Authori-zation": uni.getStorageSync('token'),
						"Content-Type": "multipart/form-data"
					}
				});

				if (response.code === 200 && response.data) {
					// 替换临时文件为上传后的URL
					const tempIndex = newFileList.findIndex(
						f => f.url === item.tempFilePath && f.temp
					);

					if (tempIndex !== -1) {
						newFileList[tempIndex] = {
							url: response.data,
							type: 'image'
						};
					}
				} else {
					throw new Error(response.message || "图片上传失败");
				}
			}

			// 更新文件列表
			fileList.value = newFileList;

			// 触发文件变化事件
			emits('file-change', fileList.value.map(f => f.url));

			uni.showToast({
				title: '图片上传完成',
				icon: 'success'
			});
		} catch (error) {
			console.error("图片上传失败:", error);

			// 移除所有临时文件
			fileList.value = fileList.value.filter(f => !f.temp);

			uni.showToast({
				title: error.message || '上传失败',
				icon: 'none'
			});
		} finally {
			// 隐藏加载提示
			uni.hideLoading();
			uploading.value = false;
		}
	};

	// 删除图片
	const handleRemoveImage = (index) => {
		fileList.value.splice(index, 1);
		emits('file-change', fileList.value.map(f => f.url));
	};

	// 监听外部传入的文件变化
	watch(() => props.initialFiles, (newFiles) => {
		// 只有当不在上传过程中时才更新文件列表
		if (!uploading.value) {
			// 比较新旧文件列表是否有变化
			const newUrls = newFiles.map(file => file.url || file);
			const currentUrls = fileList.value.map(file => file.url);

			// 只有当实际内容发生变化时才更新
			if (newUrls.length !== currentUrls.length ||
				newUrls.some(url => !currentUrls.includes(url))) {
				fileList.value = newFiles.map(file => ({
					url: file.url || file,
					type: 'image'
				}));
			}
		}
	}, {
		deep: true,
		immediate: true
	});

	// 页面隐藏时清空
	onHide(() => {
		fileList.value = [];
	});
</script>

<style scoped>
	.uploader-wrapper {
		padding: 20rpx 0;
	}

	.ppl-uploader {
		width: 120rpx;
	}

	.close-icon {
		position: absolute;
		right: -2px;
		top: -3px;
	}

	/* 添加上传中的样式 */
	.uploading-mask {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.uploading-text {
		color: white;
		font-size: 24rpx;
	}
</style>